// DDCriticalSection.h: interface 
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_DDCriticalSection_H__INCLUDED_)
#define AFX_DDCriticalSection_H__INCLUDED_

#ifndef _WIN32
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#endif


class DDCriticalSection
{
#ifdef _WIN32
public:
	DDCriticalSection(){::InitializeCriticalSection(&m_sect);}
	~DDCriticalSection(){::DeleteCriticalSection(&m_sect);}

public:
	BOOL Lock(){ ::EnterCriticalSection(&m_sect); return TRUE; }
	BOOL Unlock(){ ::LeaveCriticalSection(&m_sect); return TRUE; }

private:
	CRITICAL_SECTION m_sect;
#else
public:
	DDCriticalSection(){m_mutex = PTHREAD_MUTEX_INITIALIZER;}
	~DDCriticalSection(){pthread_mutex_destroy(&m_mutex);}

public:
	BOOL Lock(){ pthread_mutex_lock (&m_mutex); return TRUE; }
	BOOL Unlock(){ pthread_mutex_unlock(&m_mutex); return TRUE; }

private:
	pthread_mutex_t m_mutex;
#endif
};

struct DD_AUTO_LOCK
{
	DD_AUTO_LOCK(DDCriticalSection* pLock)
	{
		m_pLock = pLock;
		if( NULL != m_pLock )
		{
			m_pLock->Lock();
		}
	}
	~DD_AUTO_LOCK()
	{
		if( NULL != m_pLock )
		{
			m_pLock->Unlock();
		}
	}
	void UnLock()
	{
		if( NULL != m_pLock )
		{
			m_pLock->Unlock();
		}
	}
	void ReLock()
	{
		if( NULL != m_pLock )
		{
			m_pLock->Lock();
		}
	}
	void CancelLock()
	{
		if( NULL != m_pLock )
		{
			m_pLock->Unlock();
			m_pLock = NULL;
		}
	}
	DDCriticalSection* m_pLock;
};


#endif // !defined(AFX_TGAutoDelete_H__INCLUDED_)
